import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class RestApi {

    private String sitUri = "https://siteip.9fchaoneng.cn:7001";
//    private String sitUri = "http://localhost:8082";

    private HttpURLConnection connection;

    public String exchange(String url, RequestMethod method, String token, Map<String, Object> requestParm) throws Exception {
        init(url, method, token);
        sendRequest(convertMapToString(requestParm));
        return captureResponse();
    }

    private String convertMapToString(Map<String, Object> requestParm) {
        if (requestParm == null || requestParm.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (String key : requestParm.keySet()) {
            builder.append(key).append("=").append(requestParm.get(key)).append("&");
        }
        return builder.deleteCharAt(builder.lastIndexOf("&")).toString();
    }

    private void init(String uri, RequestMethod method, String token) throws Exception {
        URL url = new URL(sitUri + uri);
        //获取连接对象
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method.toString());
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("content-Type", "application/json");
        connection.setRequestProperty("shiro_token", token);
    }

    private void sendRequest(String urlParameters) throws IOException {
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }

    private String captureResponse() throws IOException {
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = reader.readLine()) != null) {
                builder.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null)
                reader.close();
        }
        System.out.println(builder.toString());
        return builder.toString();
    }
}
